package com.ddxz.tool.http.method;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ddxz.tool.http.exception.HttpClientException;
import com.ddxz.tool.http.factory.AbstractDdxzHttpRequest;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.IOException;
import java.util.Map;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/30
 */

public class DdxzHttpPost extends AbstractDdxzHttpRequest {
    public DdxzHttpPost(OkHttpClient client) {
        super(client);
    }

    @Override
    public String doRequest(String url, Map headers, Object entity) {
        try {
            Request.Builder builder = new Request.Builder().url(url);
            headers.forEach((key, val) -> builder.addHeader(key.toString(), val.toString()));
            RequestBody body;
            if(HEADER_JSON.equals(headers.get(CONTENT_TYPE))) {
                body = RequestBody.create(JSON.toJSONString(entity), HEADER_JSON);
            } else {
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                ((Map<String, Object>)entity).forEach((key, val)-> bodyBuilder.add(key, val.toString()));
                body = bodyBuilder.build();
            }
            builder.post(body);
            return client.newCall(builder.build()).execute().body().string();
        } catch (IOException e) {
            throw new HttpClientException("error while execute request: " + url);
        }
    }
}
